<template>
  <div class="user" style="margin-top: 20px;">
    <div style="display: flex; align-items: center; margin-bottom: 20px;margin-left: 20px;">
      <!-- 筛选条件 -->
      <el-row :gutter="50">
        <!-- 关键词筛选框 -->
        <el-col :span="12">
          <el-input v-model="filterKeyword" placeholder="请输入用户名或昵称"></el-input>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="getUsers">查询</el-button>
        </el-col>
        <el-col :span="5">
          <el-button type="success" @click="addUser()">新增</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 列表 -->
    <el-table :data="users" style="width: 1200px;"
              border
              :header-cell-style="{
                  background: '#DAF8D4',
                  color: '#333333',
                  fontWeight: 'bold',
                  fontSize: '20px',
              }">
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="用户名" prop="username"></el-table-column>
      <el-table-column label="昵称" prop="nickname"></el-table-column>
      <el-table-column label="邮箱" prop="email" width="200px"></el-table-column>
      <el-table-column label="手机号" prop="phone" width="200px"></el-table-column>
<!--      <el-table-column label="头像" width="200px">-->
<!--        <template v-slot="scope">-->
<!--          <img :src="getUserImageUrl(scope.row.id)" :alt="'User avatar for ' + scope.row.id" style="width: 100%; height: auto; object-fit: cover;" />-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="头像" width="200">
        <template v-slot="scope">
          <img :src="scope.row.avatarPath" :alt="'User avatar for ' + scope.row.id" style="width: 100%; height: auto; object-fit: cover;" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <template v-slot="scope">
          <div class="button-group">
            <!-- 编辑按钮 -->
            <el-button type="primary" size="medium" @click="editUser(scope.row)">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" size="medium" @click="deleteUser(scope.row.id)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑/新增对话框 -->
    <el-dialog
        title="编辑用户"
        :visible.sync="dialogVisible"
        width="50%"
        @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <el-form-item label="头像">
            <pic-upload-form
                v-if="dialogVisible"
                :oldAvatarUrl="oldAvatarPath"
                @file-selected="handleFileSelected"></pic-upload-form>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('form')">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>


<script>
import PicUploadForm from '../common/PicUploadForm.vue'; // 导入图片上传组件
export default {
  name : 'userView',
  components: {
    PicUploadForm // 注册图片上传组件
  },
  data() {
    return {
      filterKeyword: '',
      users: [],
      dialogVisible: false,
      oldAvatarUrl:'',
      form: {
        id: '',
        username: '',
        password: '',
        nickname: '',
        email: '',
        phone: '',
        avatarFile: '',
        avatarPath: ''
      },
      hasSelectedFile: true, // 用于追踪文件是否被选择
      fileList: [], // 用于存储预览的图片列表
      tempAvatarUrl: '', // 临时存储预览图片的URL
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '昵称不能为空', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  created() {
    this.getUsers();
  },
  computed: {
    // 计算属性，根据form.id返回旧头像的URL
    oldAvatarPath() {
      if (this.form.avatarPath) {
        return this.form.avatarPath;
      }
      // 如果没有ID，返回一个默认或空的值
      return '';
    },
  },
  methods: {
    async getUsers() {
      // 这里编写获取用户数据的逻辑
      try {
        let params = {
          pageNumber: 1,
          pageSize: 10,
          filterKeyword: this.filterKeyword
        };
        const response = await this.$http.post('system/getUsers',params);
        this.users = response.data.data; // 假设返回的数据格式为数组
      } catch (error) {
        console.error('Error fetching users:', error);
      }
    },
    getUserImageUrl(userId) {
      const timestamp = Date.now(); // 获取当前时间戳
      return `http://localhost:8888/system/get_user_image/${userId}?timestamp=${timestamp}`;
    },
    addUser() {
      // 这里编写新增用户的逻辑
      this.dialogVisible = true;
      this.resetForm()
    },
    editUser(row) {
      this.dialogVisible = true;
      this.form = Object.assign({}, row);
    },
    // 删除
    deleteUser(id) {
      this.$confirm('确认删除该用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.get(`system/deleteUser?id=${id}`)
            .then(() => {
              // 处理成功响应
              this.getUsers(); // 重新请求查询接口
              this.$message.success('删除成功');
            })
            .catch(error => {
              console.error('删除失败', error);
              this.$message.error('删除失败');
            });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    resetForm() {
      // console.log("")
    },
    handleFileSelected(file) {
      // 处理接收到的文件列表
      this.file = file;
    },
    // 保存信息
    async submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            // 创建一个新的 FormData 实例
            const formData = new FormData();

            // 遍历 this.form 的属性，并将它们添加到 FormData 实例中
            // 注意：这里不包括文件字段，因为它需要特殊处理
            for (let key in this.form) {
              if (Object.prototype.hasOwnProperty.call(this.form,key) && key !== 'avatarFile') {
                formData.append(key, this.form[key]);
              }
            }

            // 添加文件到 FormData 实例中
            // 假设 this.file 是一个 File 对象或者是一个包含 File 对象的数组
            if (this.file) {
              formData.append('avatarFile', this.file.file);
            }

            // 发送 POST 请求，使用 FormData 实例作为请求体
            this.$http.post('system/saveOrUpdateUser', formData)
                .then(() => {
                  this.getUsers(); // 重新请求查询接口
                  this.dialogVisible = false;
                })
                .catch(error => {
                  console.error('Error saving user:', error);
                });
          } catch (error) {
            console.error('Error submitting form:', error);
          }
        }
      });
    }
  },
}
</script>


<style>

.button-group {
  display: flex;
  justify-content: space-between;
}


.user {
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>
